/**
 * JAVACC DEMO 1.0
 */
package com.apache.ius.impl;

import com.apache.cache.service.CacheManager;
import com.apache.cache.service.impl.redis.RedisManagerImpl;
import com.apache.cache.util.Validator;
import com.apache.ius.plugin.MaxContentPorxyPlugin;
import com.apache.tools.DateUtils;
import com.apache.tools.FileOperate;
import org.apache.commons.io.IOUtils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Map;

/**
 * description:  处理大字段接口类实现
 *
 * @author qihan 创建时间：2017-7-25
 */
public class MaxContentPorxyPluginImpl implements MaxContentPorxyPlugin {

    private static MaxContentPorxyPluginImpl instance;

    private CacheManager cacheManager;

    String rootPath = "";

    public void init() {
        instance = this;
        cacheManager = new RedisManagerImpl();
        cacheManager.setCacheName("Max_Content_Spaces");
        rootPath = Validator.getClassLoaderPath().replace("WEB-INF/classes", "filedb");
    }

    public static MaxContentPorxyPluginImpl getInstance() {
        return instance;
    }

    /**
     * TODO 内容写入缓存.  cacheContent,dbType,key
     */
    public Object saveContent(String key, Map<String, ?> params) {
        String content = String.valueOf(params.get("cacheContent"));
        if (Validator.isNull(content))
            return "";
        String dbType = String.valueOf(params.get("dbType"));
        if ("file".equalsIgnoreCase(dbType)) {
            return saveFileInfo(key, content);
        } else {
            return saveCacheInfo(key, content);
        }
    }

    /**
     * TODO 删除内容缓存.  cacheContent,dbType,key
     */
    public void delContent(String key, String... others) {
        String dbType = "";
        if (null != others && others.length > 0)
            dbType = String.valueOf(others[0]);
        if ("file".equalsIgnoreCase(dbType)) {
            File file = new File(rootPath + "/" + key);
            if (file.exists() && file.isFile()) {
                file.delete();
            }
        } else {
            cacheManager.removeCacheObject(key);
        }
    }

    /**
     * TODO 简单描述该方法的实现功能（可选）.  key,dbType
     *
     * @see MaxContentPorxyPlugin#doContent(java.lang.String, java.lang.String[])
     */
    public Object doContent(String key, String... others) {
        String dbType = "";
        if (null != others && others.length > 0)
            dbType = String.valueOf(others[0]);
        if ("file".equalsIgnoreCase(dbType)) {
            return viewFileInfo(key);
        } else {
            return viewCacheInfo(key);
        }
    }

    private String saveCacheInfo(String key, Object obj) {
        if (Validator.isNull(key) || "fsId".equalsIgnoreCase(key))
            key = "cache_" + Validator.generate();
        cacheManager.createCacheObject(key, obj);
        return key;
    }

    private String saveFileInfo(String key, String content) {
        String filePath = "";
        String result = key;
        if (Validator.isNull(key) || "fsId".equalsIgnoreCase(key)) {
            key = DateUtils.Now.fmt_HHmmssSSS().replace(":", "") + ".dl";
            String path = DateUtils.Now.fmt_yyyyMMdd().replace("-", "/");
            filePath = rootPath + path + "/";
            FileOperate.getInstance().newCreateFolder(filePath);
            filePath = filePath + key;
            result = path + "/" + key;
        } else {
            filePath = rootPath + key;
        }
        FileOperate.getInstance().newCreateFile(filePath, content);
        return result;
    }

    private String viewCacheInfo(String key) {
        if (cacheManager.checkCacheObject(key)) {
            return String.valueOf(cacheManager.getCacheCloneByKey(key));
        }
        return "";
    }

    private String viewFileInfo(String key) {
        InputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(rootPath + key));
            String content = IOUtils.toString(in, "UTF-8");
            return content;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(in);
        }
        return "";
    }
}
